package org.googlecode.lightning.search.parse.parser.pdf;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.daragon.fulltext.parse.parser.SimpleDocParser;
import org.daragon.fulltext.segment.Holder;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;

/**
 * 
 * @author daragon
 * 
 */
public class PDFParser extends SimpleDocParser {
	private final static Log log = LogFactory.getLog(PDFParser.class);

	public static final String MIME_TYPE = "application/pdf";

	/**
	 * 
	 * Extract the text from a PDF document.
	 * <p>
	 * 
	 * @param holder
	 *            The file's Content to extract text.
	 * @return The extracted text.
	 * @throws IOException
	 * 
	 */
	protected String extractText(Holder holder) throws IOException {
		ByteArrayInputStream is = new ByteArrayInputStream(holder.getContent());
		PDDocument pddoc = null;

		String text = null;
		try {
			pddoc = PDDocument.load(is);
			if (pddoc.isEncrypted()) {
				log.error("The Pdf document " + holder.getFilename()
						+ "is encrypted!");
				// 对于加密文件不进行处理
				return null;
			}

			PDFTextStripper pdfExtractor = new PDFTextStripper();
			text = pdfExtractor.getText(pddoc);
		} catch (OutOfMemoryError e) {
			throw new IOException("pdfbox out of memory error");
		} finally {
			if (pddoc != null) {
				pddoc.close();
			}
			IOUtils.closeQuietly(is);
		}
		return text;
	}
}